package com.xyzq.hs;

import java.util.ArrayList;
import java.util.List;

import com.xyzq.hs.util.ParameterUtils;

public class TSTemplate  {

	/**
	 * 同时执行多个功能号
	 * @param functionNos
	 * @param params
	 * @return
	 */
	public List<ResultSet> batchExcute(List<Integer> functionNos,
			List<? extends Object> params) {
		TSClient client = TSClientFactory.getClient();
		Request request = null;
		int size = functionNos.size();
		List<RequestEntry> requestEntries = new ArrayList<RequestEntry>();
		for (int i = 0; i < size; i++) {
			Integer functionNo = functionNos.get(i);
			String param = null;
			Object object = params.get(i);
			if (object instanceof String) {
				// e.g: request_num=5&found_account=35517
				param = object.toString();
			} else {
				param = ParameterUtils.buildParam(object);
			}
			RequestEntry requestEntry = new RequestEntry(functionNo, param);
			requestEntries.add(requestEntry);
		}
		request = new Request(requestEntries);
		Response response = client.doPost(request);
		return response.getResultSets();
	}
	
	
	/**
	 * 执行单个功能号
	 * @param functionNos
	 * @param params
	 * @return
	 */
	public ResultSet excute(Integer functionNo,Object param) {
		List<Integer> functionNos = new ArrayList<Integer>();
		functionNos.add(functionNo);
		List<Object> params = new ArrayList<Object>();
		params.add(param);
		List<ResultSet> list = this.batchExcute(functionNos, params);
		return list.get(0);
	}
	
	public Object  excute(int functionNo, Object param, ResultSetCallBack action,
			Result result) {
		ResultSet rs = this.excute(functionNo, param);
		if(result!=null){
			result.setResponseCode(rs.getResponseCode());
			result.setErrorMessage(rs.getErrorMessage());
		}
		if(rs.getResponseCode()==0){
				return action.doInResultSet(rs);
		}
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public <T> List<T> excuteForList(int functionNo, Object param, Class<T> output,
			Result result) {
		return (List<T>)this.excute(functionNo, param, new ListResultSetCallBack(output), result);
	}
	
	@SuppressWarnings("unchecked")
	public <T> T  excuteForObject(int functionNo, Object param, Class<T> output,
			Result result) {
		return (T)this.excute(functionNo, param, new ObjectResultSetCallBack(output), result);
	}
	

	public <T> List<T> queryForList(int functionNo, Object param, Class<T> output) {
		Result result = new Result();
		List<T> list = this.excuteForList(functionNo, param, output, result);
		if (result.getResponseCode() != 0) {
			throw new TSException(result.getResponseCode(),
					result.getErrorMessage());
		}
		return list;
	}
	
	public <T> T queryForObject(int functionNo, Object param, Class<T> output) {
		Result result = new Result();
		T t = this.excuteForObject(functionNo, param, output, result);
		if (result.getResponseCode() != 0) {
			throw new TSException(result.getResponseCode(),
					result.getErrorMessage());
		}
		return t;
	}


}
